package com.llt.chatroom.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.llt.chatroom.component.OnlineUserManager;
import com.llt.chatroom.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Slf4j
@Component
public class AddFriendController extends TextWebSocketHandler {
    @Autowired
    OnlineUserManager onlineUserManager;

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 会在建立连接成功够后，自动调用
        log.info("websocket2连接成功");

        User user = (User) session.getAttributes().get("user");
        if (user == null) {
            return;
        }
        log.info("获取到的 userid: " + user.getUserId());

        // 上线
        onlineUserManager.online(user.getUserId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // webSocket收到消息的时候自动调用
        log.info("收到消息: " + message.toString());

        // session 中记录了通信双方是谁
        session.sendMessage(message);

        // 1.获取到当前用户信息
        User user = (User) session.getAttributes().get("user");
        if (user == null) {
            log.error("user == null");
            return;
        }

        // 2. 针对请求进行解析, 转 json 为 java 对象
        MessageRequest req = objectMapper.readValue(message.getPayload(), MessageRequest.class);
        if (req.getType().equals("addFriend")) {
            log.info("正在执行添加好友逻辑");
            // 进行消息转发
            addFriend(user, req);
        }else {
            log.error("type 有误" + message.getPayload());
        }
    }

    private void addFriend(User user, MessageRequest req) {

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 连接出现异常时自动调用
        log.error("websocket2连接异常: " + exception.toString());

        User user = (User) session.getAttributes().get("user");
        if (user == null) {
            return;
        }

        // 下线
        onlineUserManager.offline(user.getUserId(), session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 正常关闭后自动调用
        log.info("websocket2连接关闭: " + status.toString());

        User user = (User) session.getAttributes().get("user");
        if (user == null) {
            return;
        }

        // 下线
        onlineUserManager.offline(user.getUserId(), session);
    }
}
